package com.wh.wisdomsite.xbox.server.controller.us;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.us.OfficeIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.session.ServerSessionUser;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.us.entity.Company;
import com.wh.wisdomsite.xbox.us.entity.Office;
import com.wh.wisdomsite.xbox.us.service.ICompanyService;
import com.wh.wisdomsite.xbox.us.service.IOfficeService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/***
 *部门管理控制器Controller
 * @author 杨世强
 * @date 16:47 2018/8/2
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/office")
public class OfficeController {
    private static final Log logger = LogFactory.getLog(OfficeController.class);

    @Autowired
    private IOfficeService iOfficeService;

    @Autowired
    private ICompanyService iCompanyService;

    /**
     * 跳转到部门管理页面
     *
     * @return
     */
    @RequiresPermissions("rules:us_office_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index() {
        return "us/office/officeList";

    }

    /**
     * 根据条件获取部门树形
     * @param response 响应对象
     * @param in 输出参数
     */
    @RequiresPermissions("rules:us_office_find")
    @RequestMapping(value = "/getOfficeTree.do")
    public void getTreeOffice(HttpServletResponse response, OfficeIn in) {
        try {
            logger.info("加载树形菜单-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<Office> page = new Page<Office>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            EntityWrapper<Office> ewOffice = new EntityWrapper<Office>();
            ewOffice.setEntity(new Office());
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewOffice = setEntityWrapper(ewOffice, "co", "off");
            }
            if(null != in.getCompanyId()){
                ewOffice.eq("off.companyId",in.getCompanyId());
            }
            if(StringUtils.isNotEmpty(in.getName())){
                ewOffice.like("off.name",in.getName());
            }
            ewOffice.eq("off.dataState",1);
            ewOffice.orderBy("off.officeCode",true);
            Page<Office> officePage = iOfficeService.getPage(page,ewOffice);
            JSONObject json = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            if(officePage.getRecords().size() > 0){
                List<Office> officeList = iOfficeService.getMenuListForSerch(officePage.getRecords());
                for (Office officeModel : officeList) {
                    JSONObject jsonObject = new JSONObject(officeModel);
                    jsonObject.put("createDateFormat", DateTool.format(officeModel.getCreateDate(), "yyyy-MM-dd"));

                    jsonArray.put(jsonObject);
                }
            }
            json.put("total", officePage.getTotal());
            json.put("rows", jsonArray);
            ResManager.getTextOut(response).print(json);
            logger.info("加载树形菜单-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载树形菜单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 根据companyId获取部门树形结构
     * @param response
     * @param companyId
     */
    @RequestMapping(value = "/getTree.do")
    public void getTree(HttpServletResponse response, Integer companyId) {
        try {
            logger.info("获取树形菜单-->>开始");
            EntityWrapper<Office> ewOffice = new EntityWrapper<Office>();
            ewOffice.setEntity(new Office());
            Boolean isAdmin = UserUtils.isSysAdmin();
            if(!isAdmin){
                ewOffice = setEntityWrapper(ewOffice, "co", "off");
            }
            if(null != companyId){
                ewOffice.eq("off.companyId",companyId);
            }
            ewOffice.eq("off.dataState", "1");
            ewOffice.orderBy("off.officeCode", true);
            List<Office> allOfficeList = iOfficeService.getList(ewOffice);
            JSONArray jsonArray = iOfficeService.toTreeOffice(allOfficeList,isAdmin);
            ResManager.getTextOut(response).print(jsonArray);
            logger.info("获取树形结构-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("获树形结构-->>Exception" + e.getMessage());
        }
    }


    /**
     * 部门详情
     *
     * @param in
     * @param request
     * @return
     */
    @RequiresPermissions("rules:ba_commonDict_view")
    @RequestMapping("officeDesc.do")
    public String officeDescDetails(OfficeIn in, HttpServletRequest request) {
        logger.info("部门详情-->>开始");
        Office office = iOfficeService.selectById(in.getOfficeId());
        if(null != office.getCreateBy()){
            office.setCreateBy(UserMapManager.getUserLoginNameInMap(office.getCreateBy()));
        }
        if(null!=office.getUpdateBy()){
            office.setUpdateBy(UserMapManager.getUserLoginNameInMap(office.getUpdateBy()));
        }
        request.setAttribute("office", office);
        logger.info("部门详情-->>结束");
        return "us/office/officeDesc";
    }

    /**
     * 删除部门
     *
     * @param office
     * @param response
     */
    @RequiresPermissions("rules:us_office_del")
    @RequestMapping(value = "del.do", method = RequestMethod.GET)
    public void del(Office office, HttpServletResponse response) {
        try {
            logger.info("删除部门-->>开始");
            iOfficeService.deleteById(office.getOfficeId());
            logger.info("删除部门-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除部门-->>Exception" + e.getMessage());
        }
    }


    /**
     * 更新或修改部门
     * @param response
     * @param office
     */
    @RequiresPermissions("rules:us_office_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Office office,HttpServletResponse response) {
        try {
            logger.info("保存部门信息-->>开始");
            Integer sessionCompId = UserUtils.getCurrentUser().getCompanyId();
            Integer companyId = office.getCompanyId();
            Company company = iCompanyService.selectById(companyId);
            String compCode = company.getCompCode();
            EntityWrapper<Office> ewOffice = new EntityWrapper<Office>();
            ewOffice.eq("off.companyId", companyId);
            ewOffice.eq("off.parentId", 0);
            ewOffice.eq("off.dataState", "1");
            ewOffice.orderBy("off.officeCode",true);
            List<Office> officeList = iOfficeService.getList(ewOffice);
            //判断当前公司下的部门，是否为空
            if (null != officeList && officeList.size() > 0) {
                //如果主键不为空，则更新
                if (null != office.getOfficeId()) {
                    // 获取原部门数据
                    Office officeInitially = iOfficeService.getOfficeById(office.getOfficeId());
                    Integer parentId = office.getParentId();
                    String officeCode = officeInitially.getOfficeCode();
                    // parentId为空表示页面没有选中，则赋值为0(根级）
                    if (parentId == null) {
                        parentId = 0;
                    }
                    // 如果父级id变化，当前对象编码需要改变
                    if(parentId != null && officeInitially.getParentId() != parentId){
                        officeCode = iOfficeService.getOfficeCode(officeList, parentId,compCode);
                    }
                    office.setOfficeCode(officeCode);
                    office.setParentId(parentId);
                    String sss = UserUtils.getCurrentUser().getUsId();
                    office.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                    office.setUpdateDate(new Date());
                    iOfficeService.updateById(office);
                    // 如果父级id变化，更新当前对象的子集编码
                    if(parentId != null && officeInitially.getParentId() != parentId){
                        iOfficeService.updateChildNode(office,sessionCompId);
                    }
                } else {
                    Integer parentId = office.getParentId();
                    String officeCode = iOfficeService.getOfficeCode(officeList, parentId,compCode);
                    //parentId为空表示页面没有选中，则赋值为0(根级）
                    if (parentId == null) {
                        parentId = 0;
                    }
                    office.setOfficeCode(officeCode);
                    office.setParentId(parentId);
                    office.setCreateDate(new Date());
                    office.setCreateBy(UserUtils.getCurrentUser().getUsId());
                    iOfficeService.insert(office);
                }
            } else {
                //公司下部门为空，对新添加的部门初始化编码
                String officeCode = compCode + "-" + "000";
                office.setOfficeCode(officeCode);
                office.setCreateBy(UserUtils.getCurrentUser().getUsId());
                office.setParentId(0);
                if(null != office.getOfficeId()){
                    iOfficeService.updateById(office);
                }else{
                    office.setCreateDate(new Date());
                    iOfficeService.insert(office);
                }
            }
            response.getWriter().write(JsonUtil_Org.returnTrue("保存部门信息成功"));
            logger.info("保存部门信息-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("保存部门信息-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转至添加页面
     *
     * @return
     */
    @RequestMapping("/toOffice")
    public ModelAndView toAddOffice(String officeId, HttpServletRequest request) {
        logger.info("添加修改部门跳转-->>开始");
        try {
            if (StringUtils.isNotEmpty(officeId)) {
                Office office = iOfficeService.getOfficeById(Integer.valueOf(officeId));
                request.setAttribute("office", office);
                logger.info("添加修改部门跳转-->>开始");
            }
            Integer companyId = UserUtils.getCurrentUser().getCompanyId();
            request.setAttribute("DefaultCompany",companyId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加修改部门-->>Exception" + e.getMessage());
        }
        return new ModelAndView("us/office/officeOption");
    }

    /**
     * 根据权限设置查询范围
     * @param ew
     * @param companyTableAlias
     * @param officeTableAlias
     * @return
     */
    public EntityWrapper setEntityWrapper(EntityWrapper ew, String companyTableAlias,
                                                 String officeTableAlias) {
        ServerSessionUser serverSessionUser = UserUtils.getServerSessionUser();
        String dataScope = serverSessionUser.getDataScope();
        //设置一个查询用的代码
        String codeForFind = null;
        switch (dataScope) {
            case "1":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.like(companyTableAlias + ".compCode", codeForFind);
                }
                break;
            case "2":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq(companyTableAlias + ".compCode", codeForFind);
                }
                break;
            case "3":
                codeForFind = serverSessionUser.getEmployee().getOffice().getOfficeCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.like(officeTableAlias +".officeCode", codeForFind);
                }
                break;
            case "4":
                codeForFind = serverSessionUser.getEmployee().getOffice().getOfficeCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq(officeTableAlias + ".officeCode", codeForFind);
                }
                break;
            case "5":
                codeForFind = serverSessionUser.getEmployee().getOffice().getOfficeCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq(officeTableAlias + ".officeCode", codeForFind);
                }
                break;
            default:break;
        }
        return ew;
    }

}






